<?php declare(strict_types=1);


namespace App\Api\V2\Controller\Bill\User;

use App\Api\Controllers\BaseController;
use App\Models\Store;
use App\Models\StorePayWay;
use App\Models\Stores;
use App\Models\StoreWaysDesc;
use App\Services\Count\BillLogCountService;
use App\Services\Count\StoreCompanyCountService;
use App\Services\Count\UserBillCountService;
use App\Services\Count\UserService;
use App\Services\PrintSqlService;
use App\Traits\ResponseTrait;
use App\Util\ExeclUtil;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CountController extends BaseController
{
    use ResponseTrait;


    //打标数据 只有总店
    const MARK = [
        101 => 1,
        747 => 4,
        874 => 5,
        1002 => 6
    ];


    //商户交易统计
    public function merchantExchangeCount(Request $request): string
    {
        try {
            //
            $user = $this->parseToken();
            $user_id = $user->user_id;
            $agent_id = empty($request->get("agent_id")) ? $user_id : (int)$request->get("agent_id");    //接受到代理商ID。需要查看 本身+下级的

            $mark = $request->get("mark", 0);
            //获取 $user_id 的下级代理商ID
//            $service = new UserService();
//            $userSub = $service->getSub($user_id);
//            $userSubIds = array_column($userSub, "id");
            $storeSubsSearch = [
                [
                    "store_name" => "全部",
                    "store_id" => "",
                    "isSub" => -1,
                    "checked" => 0
                ]
            ];
            if ($mark == 1) {
                if (!empty($agent_id)) {
                    $user_id = $agent_id;
                }
                if (!in_array($user_id, array_keys(self::MARK))) {
                    throw new \Exception("您不是打标代理商无法查询");
                }
                $store = Store::query()->where(["ascription" => self::MARK[$user_id]])->get();
                list($oem_id, $agent1_id, $agent2_id, $agent3_id, $agent4_id) = [0, 0, 0, 0, 0];
                $storeIds = $storePids = [];
                foreach ($store as $val) {
                    $storePids[] = $val->store_id;
                    $storeSubsSearch[] = [
                        "store_name" => $val->store_name,
                        "store_id" => $val->store_id,
                        "isSub" => $val->pid > 0 ? 1 : 0,
                        "checked" => 0
                    ];
                }
            } else {
                $userService = new UserService();
                list($idValues, $column) = $userService->handleUserAccountRelation((int)$agent_id);
                list($oem_id, $agent1_id, $agent2_id, $agent3_id, $agent4_id) = $idValues;
                list($profit_column, $fee_column) = $column;
                //在这里获取总店和分店
                $storeId = $request->get("store_id");
                $storeIds = $storePids = [];
                if (!empty($storeId)) {
                    $store = Store::query()->where("store_id", $storeId)->first();
                    if (empty($store)) {
                        throw new \Exception("店铺不存在");
                    }
                    $storeSubsSearch[] = [
                        "store_name" => $store->store_name,
                        "store_id" => $store->store_id,
                        "isSub" => $store->pid > 0 ? 1 : 0,
                        "checked" => 0
                    ];
                    $storeSubs = Store::query()->where("pid", $store->id)->get()->toArray();
                    foreach ($storeSubs as $v) {
                        $storeIdSub[] = $v["store_id"];
                        $storeSubsSearch[] = [
                            "store_name" => $v["store_name"],
                            "store_id" => $v["store_id"],
                            "isSub" => $v["pid"] > 0 ? 1 : 0,
                            "checked" => 0
                        ];
                    }
                    $storeIds = array_merge([$storeId], $storeIdSub ?? []);
                }
            }
            //条件
            $where = [
                "oem_id" => $oem_id,
                "agent1_id" => $agent1_id,
                "agent2_id" => $agent2_id,
                "agent3_id" => $agent3_id,
                "agent4_id" => $agent4_id,
                "curHdIndex" => $request->get("curHdIndex"),
                "startDate" => $request->get("startDate"),
                "endDate" => $request->get("endDate"),
                "store_id" => $storeIds,
                "store_pid" => $storePids,
                "pay_type" => $request->get("pay_type"),
                "company" => $request->get("company"),
                "money" => $request->get("money"),
                "cashier" => $request->get("merchant_id"),
                "receive_model" => $request->get("receive_model"),
                "mark" => $mark,
                "search_store_id" => $request->get("search_store_id"),
            ];
//            PrintSqlService::listen();
            $service = new UserBillCountService();
            $storeSubsSearch = array_map(function ($v) use ($where) {
                if ($v["store_id"] == $where["search_store_id"]) {
                    $v["checked"] = 1;
                }
                return $v;
            }, $storeSubsSearch);
//            PrintSqlService::listen();
            $data = $service->merchantGet($where);
            return $this->successResponse("ok", ["data" => $data, "storeSubsSearch" => $storeSubsSearch]);
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }


    public function merchantExchangeCountList(Request $request): string
    {
        $user = $this->parseToken();
        $user_id = $user->user_id;
        $agent_id = empty($request->get("agent_id")) ? $user_id : (int)$request->get("agent_id");    //接受到代理商ID。需要查看 本身+下级的

        $mark = $request->get("mark", 0);
        //获取 $user_id 的下级代理商ID
//            $service = new UserService();
//            $userSub = $service->getSub($user_id);
//            $userSubIds = array_column($userSub, "id");
        try {
            if ($mark == 1) {
                if (!empty($agent_id)) {
                    $user_id = $agent_id;
                }
                if (!in_array($user_id, array_keys(self::MARK))) {
                    throw new \Exception("不是打标代理商");
                }
                $store = Store::query()->where(["ascription" => self::MARK[$user_id]])->get();
                list($oem_id, $agent1_id, $agent2_id, $agent3_id, $agent4_id) = [0, 0, 0, 0, 0];
                $storeIds = $storePids = [];
                foreach ($store as $val) {
                    $storePids[] = $val->store_id;
                }
            } else {
                $userService = new UserService();
                list($idValues, $column) = $userService->handleUserAccountRelation((int)$agent_id);
                list($oem_id, $agent1_id, $agent2_id, $agent3_id, $agent4_id) = $idValues;
                list($profit_column, $fee_column) = $column;
                //在这里获取总店和分店
                $storeId = $request->get("store_id");
                $storeIds = $storePids = [];
                if (!empty($storeId)) {
                    $store = Store::query()->where("store_id", $storeId)->first();
                    if (empty($store)) {
                        throw new \Exception("店铺不存在");
                    }
                    $storeIdSub = Store::query()->where("pid", $store->id)->pluck("store_id")->toArray();
                    $storeIds = array_merge([$storeId], $storeIdSub);
                }
            }
            //条件
            $where = [
                "oem_id" => $oem_id,
                "agent1_id" => $agent1_id,
                "agent2_id" => $agent2_id,
                "agent3_id" => $agent3_id,
                "agent4_id" => $agent4_id,
                "curHdIndex" => $request->get("curHdIndex"),
                "startDate" => $request->get("startDate"),
                "endDate" => $request->get("endDate"),
                "store_id" => $storeIds,
                "store_pid" => $storePids,
                "pay_type" => $request->get("pay_type"),
                "company" => $request->get("company"),
                "money" => $request->get("money"),
                "cashier" => $request->get("merchant_id"),
                "receive_model" => $request->get("receive_model")
            ];
            $service = new UserBillCountService();
//            PrintSqlService::listen();
            $result = $service->merchantGetList($where);

            return $this->successResponse("ok", ["data" => $result]);
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }


    public function merchantExchangeCountListExport(Request $request): string
    {
        $user = $this->parseToken();
        $user_id = $user->user_id;
        $agent_id = empty($request->get("agent_id")) ? $user_id : (int)$request->get("agent_id");    //接受到代理商ID。需要查看 本身+下级的

        try {
            $mark = $request->get("mark", 0);
            //获取 $user_id 的下级代理商ID
//            $service = new UserService();
//            $userSub = $service->getSub($user_id);
//            $userSubIds = array_column($userSub, "id");
            if ($mark == 1) {
                if (!empty($agent_id)) {
                    $user_id = $agent_id;
                }
                if (!in_array($user_id, array_keys(self::MARK))) {
                    throw new \Exception("不是打标代理商");
                }
                $store = Store::query()->where(["ascription" => self::MARK[$user_id]])->get();
                list($oem_id, $agent1_id, $agent2_id, $agent3_id, $agent4_id) = [0, 0, 0, 0, 0];
                $storeIds = $storePids = [];
                foreach ($store as $val) {
                    $storePids[] = $val->store_id;
                }
            } else {
                $userService = new UserService();
                list($idValues, $column) = $userService->handleUserAccountRelation((int)$agent_id);
                list($oem_id, $agent1_id, $agent2_id, $agent3_id, $agent4_id) = $idValues;
                list($profit_column, $fee_column) = $column;
                //在这里获取总店和分店
                $storeId = $request->get("store_id");
                $storeIds = $storePids = [];
                if (!empty($storeId)) {
                    $store = Store::query()->where("store_id", $storeId)->first();
                    if (empty($store)) {
                        throw new \Exception("店铺不存在");
                    }
                    $storeIdSub = Store::query()->where("pid", $store->id)->pluck("store_id")->toArray();
                    $storeIds = array_merge([$storeId], $storeIdSub);
                }
            }
            //条件
            $where = [
                "oem_id" => $oem_id,
                "agent1_id" => $agent1_id,
                "agent2_id" => $agent2_id,
                "agent3_id" => $agent3_id,
                "agent4_id" => $agent4_id,
                "curHdIndex" => $request->get("curHdIndex"),
                "startDate" => $request->get("startDate"),
                "endDate" => $request->get("endDate"),
                "store_id" => $storeIds,
                "store_pid" => $storePids,
                "pay_type" => $request->get("pay_type"),
                "company" => $request->get("company"),
                "money" => $request->get("money"),
                "cashier" => $request->get("merchant_id"),
                "receive_model" => $request->get("receive_model"),
                "mark" => $mark,
                "search_store_id" => $request->get("search_store_id"),
            ];
            $service = new UserBillCountService();
//            PrintSqlService::listen();
            $result = $service->merchantGetList($where);
            $title = [
                "账单日期", "店铺名称", "通道名称", "总交易金额", "总退款金额", "总实收", "总手续费", "总订单数", "总退款数",
            ];
            $value = [];
            //写入execl
            foreach ($result as $k => $v) {
                $value[] = [
                    $v["day"],
                    $v["store_name"],
                    $v["company_name"],
                    $v["total_fee"],
                    $v["refund_fee"],
                    $v["merchant_actual_receipt"],
                    $v["fee_amount"],
                    $v["total_num"],
                    $v["refund_num"],
                ];
            }
            //写入excel
            $util = new ExeclUtil();
            $fileName = "总账单的店铺明细" . ($where["month"] ?? date("Y-m-d")) . "_" . time() . ".csv";
            $filePath = public_path("/uploads/csv/" . date("Y/md", time()) . "/");
            if (!is_dir($filePath)) {
                mkdir($filePath, 0777, true);
            }
            $util->exportToExcel($filePath . $fileName, [], $title, $value);
            $url = $util->uploadOss($filePath . $fileName, $fileName);
            //删除文件
            if (file_exists($filePath . $fileName)) {
                unlink($filePath . $fileName);
            }
            return $this->successResponse("ok", ["data" => $url]);
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }


    public function merchantExchangeCountV2(Request $request): string
    {

        try {

            //
            $user = $this->parseToken();
            $user_id = $user->user_id;
            //获取 $user_id 的下级代理商ID
            $userService = new UserService();
            list($idValues, $column) = $userService->handleUserAccountRelation($user_id);
            list($oem_id, $agent1_id, $agent2_id, $agent3_id, $agent4_id) = $idValues;
            list($profit_column, $fee_column) = $column;

            //在这里获取总店和分店
            $storeId = $request->get("store_id");
            $storeIds = [];
            if (!empty($storeId)) {
                $store = Store::query()->where("store_id", $storeId)->first();
                if (empty($store)) {
                    throw new \Exception("店铺不存在");
                }
                $storeIdSub = Store::query()->where("pid", $store->id)->pluck("store_id")->toArray();
                $storeIds = array_merge([$storeId], $storeIdSub);
            }

            //条件
            $where = [
                "oem_id" => $oem_id,
                "agent1_id" => $agent1_id,
                "agent2_id" => $agent2_id,
                "agent3_id" => $agent3_id,
                "agent4_id" => $agent4_id,
                "curHdIndex" => $request->get("curHdIndex"),
                "startDate" => $request->get("startDate"),
                "endDate" => $request->get("endDate"),
                "store_id" => $storeIds,
                "pay_type" => $request->get("pay_type"),
                "company" => $request->get("company"),
                "money" => $request->get("money"),
                "cashier" => $request->get("merchant_id"),
                "receive_model" => $request->get("receive_model")
            ];

            $service = new BillLogCountService();

            $data = $service->merchantGet($where);

            return $this->successResponse("ok", ["data" => $data]);
        } catch (\Exception $e) {
            return $this->successResponse($e->getMessage());
        }
    }


    //门店交易统计
    public function storeExchangeCount(Request $request): string
    {
        try {

            $user = $this->parseToken();
            $user_id = $user->user_id;
            //获取 $user_id 的下级代理商ID
            $service = new UserService();
            $userSub = $service->getSub($user_id);
            $userSubIds = array_column($userSub, "id");

            $page = (int)$request->get("page", 1);
            $pagesize = (int)$request->get("pagesize", 10);

            $storeQuery = Store::query()->where("pid", "=", 0)->whereIn("user_id", $userSubIds);

            $total = (clone $storeQuery)->count();
            $lists = (clone $storeQuery)->select(['id', 'store_id', 'store_name'])->offset(($page - 1) * $pagesize)->limit($pagesize)->get()->toArray();
            $storeIds = array_column($lists, "store_id");
//            //开始统计
            $where = [
                "curHdIndex" => $request->get("curHdIndex", 1),
                "startDate" => $request->get("startDate", ""),
                "endDate" => $request->get("endDate", ""),
                "receive_model" => $request->get("receive_model"),
                "store_id" => $storeIds
            ];
            $service = new UserBillCountService();
            list($data, $countTemplate) = $service->storeGet($where);
            foreach ($lists as $k => $v) {
                $v["count"] = $data[$v["store_id"]] ?? $countTemplate;
                $lists[$k] = $v;
            }
            return $this->successResponse("ok", [
                "total" => $total,
                "data" => $lists
            ]);
        } catch (\Exception $e) {
            return $this->successResponse($e->getMessage());
        }
    }

    //渠道交易统计
    public function storeCompanyExchangeCount(Request $request): string
    {
        try {
            $user = $this->parseToken();
            $user_id = $user->user_id;
            //获取 $user_id 的下级代理商ID
            $service = new UserService();
            $userSub = $service->getSub($user_id);
            $userSubIds = array_column($userSub, "id");

            $page = (int)$request->get("page", 1);
            $pagesize = (int)$request->get("pagesize", 20);

            $storeQuery = Store::query()->where("pid", "=", 0)->whereIn("user_id", $userSubIds);

            $total = (clone $storeQuery)->count();
            $lists = (clone $storeQuery)->select(['id', 'store_id', 'store_name'])->offset(($page - 1) * $pagesize)->limit($pagesize)->get()->toArray();

            $storeIds = array_column($lists, "store_id");

            //获取店铺的所有支付方式
            $storeCompany = StorePayWay::query()
                ->select(["store_id", "company"])
                ->whereIn("store_id", $storeIds)
//                ->where("status", 1)
                ->groupBy(["store_id", "company"])
                ->get()->toArray();
            $storeMapCom = [];
            foreach ($storeCompany as $k => $v) {
                $storeMapCom[$v["store_id"]][] = $v["company"];
            }

            $companyName = StoreWaysDesc::query()->select(["company", "company_name"])->groupBy(["company", "company_name"])->get()->toArray();
            $companyName = array_combine(array_column($companyName, "company"), $companyName);

            foreach ($lists as $k => $v) {
                $v["companyArray"] = $storeMapCom[$v["store_id"]] ?? [];
                $lists[$k] = $v;
            }

//            //开始统计
            $where = [
                "curHdIndex" => $request->get("curHdIndex", 1),
                "startDate" => $request->get("startDate", ""),
                "endDate" => $request->get("endDate", ""),
                "receive_model" => $request->get("receive_model"),
                "store_id" => $storeIds
            ];
            $service = new UserBillCountService();
            list($data, $countTemplate) = $service->companyGet($where);
            foreach ($lists as $k => $v) {
                foreach ($v["companyArray"] as $kC => $vCompany) {
                    $tmp = [
                        "c" => $data[$v["store_id"]][$vCompany] ?? $countTemplate,
                        "company" => $vCompany,
                        "company_name" => $companyName[$vCompany]["company_name"] ?? ""
                    ];
                    $v["countArray"][] = $tmp;
                }
                unset($v["companyArray"]);
                $lists[$k] = $v;
            }
            return $this->successResponse("ok", [
                "total" => $total,
                "data" => $lists
            ]);
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }


    public function storeCompanyGroupCountList(Request $request): string
    {
        try {
            $user = $this->parseToken();
            $user_id = $user->user_id;
            //获取 $user_id 的下级代理商ID
            $service = new UserService();
            $userSub = $service->getSub($user_id);
            $userSubIds = array_column($userSub, "id");

            $store_created_start_date = $request->input("store_created_start_date");
            if (empty($store_created_start_date)) {
                $store_created_start_date = date("Y-m-d 00:00:00", time());
            }
            $store_created_end_date = $request->input("store_created_end_date");
            if (empty($store_created_end_date)) {
                $store_created_end_date = date("Y-m-d 23:59:59", time());
            }
            $where = [
                "store_created_start_date" => date("Y-m-d 00:00:00", strtotime($store_created_start_date)),
                "store_created_end_date" => date("Y-m-d 23:59:59", strtotime($store_created_end_date)),
                "store_id" => $request->input("store_id"),
                "user_id" => $userSubIds,
                "page" => (int)$request->input("page", 1),
                "pagesize" => (int)$request->input("pagesize", 20)
            ];
            $service = new StoreCompanyCountService();
            list($total, $lists) = $service->storeCompanyGroupCountList($where);
            return $this->successResponse("ok", [
                "total" => $total,
                "data" => $lists
            ]);
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }


    public function storeCompanyGroupCountListExport(Request $request)
    {
        try {
            $user = $this->parseToken();
            $user_id = $user->user_id;
            //获取 $user_id 的下级代理商ID
            $service = new UserService();
            $userSub = $service->getSub($user_id);
            $userSubIds = array_column($userSub, "id");
            $store_created_start_date = $request->input("store_created_start_date");
            if (empty($store_created_start_date)) {
                $store_created_start_date = date("Y-m-d 00:00:00", time());
            }
            $store_created_end_date = $request->input("store_created_end_date");
            if (empty($store_created_end_date)) {
                $store_created_end_date = date("Y-m-d 23:59:59", time());
            }
            $where = [
                "store_created_start_date" => date("Y-m-d 00:00:00", strtotime($store_created_start_date)),
                "store_created_end_date" => date("Y-m-d 23:59:59", strtotime($store_created_end_date)),
                "store_id" => $request->input("store_id"),
                "user_id" => $userSubIds,
            ];
            $service = new StoreCompanyCountService();
            list($total, $lists) = $service->storeCompanyGroupCountList($where, false);

            //在这里导出
            $title = [
                "门店id", "门店名称", "创建时间", "通道", "总交易金额", "退款金额"
            ];
            $value = [];
            //写入execl
            foreach ($lists as $k => $v) {
                $value[] = [
                    $v["store_id"],
                    $v["store_name"],
                    $v["store_created_at"],
                    $v["company_name"],
                    $v["total_fee"],
                    $v["refund_fee"],
                ];
            }
            //写入excel
            $util = new ExeclUtil();
            $fileName = "新增商户流水导出" . ($where["month"] ?? date("Y-m-d")) . "_" . time() . ".csv";
            $filePath = public_path("/uploads/csv/" . date("Y/md", time()) . "/");
            if (!is_dir($filePath)) {
                mkdir($filePath, 0777, true);
            }
            $util->exportToExcel($filePath . $fileName, [], $title, $value);
            $url = $util->uploadOss($filePath . $fileName, $fileName);
            //删除文件
            if (file_exists($filePath . $fileName)) {
                unlink($filePath . $fileName);
            }
            return $this->successResponse("ok", [
                "url" => $url,
            ]);
        } catch (\Exception $e) {
            return $this->errorResponse($e->getMessage());
        }
    }


}